package com.plian.system.service.fa.nplcancelmaintain;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.plian.Tools.*;
import com.plian.Tools.office.WordUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.UserCache;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.dao.fa.nplcancelmaintain.NPLCancelMaintainDao;
import com.plian.system.dao.fa.nplcancelmaintainsubli.NPLCancelMaintainSubliDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.dao.wf.WfCompletedTaskMapper;
import com.plian.system.entity.fa.nplcancelmaintain.CqzcNplcancelmaintain;
import com.plian.system.entity.fa.nplcancelmaintain.CqzcNplcancelmaintainsublia;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.mapper.fa.nplcancelmaintain.CqzcNplcancelmaintainMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.WfCompletedTask;
import com.plian.system.model.page.Page;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pm.property.PropertyService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.user.ISysUserService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.yth.YthResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.FormStatusConstant.*;
import static com.plian.system.constant.sys.FormTypeConstant.CQZC_NPL_CANCEL_MAINTAIN;

@Slf4j
@Service
public class NPLCancelMaintainService implements BaseFlowService {
    @Autowired
    NPLCancelMaintainDao nPLCancelMaintainDao;
    @Autowired
    NPLCancelMaintainSubliDao nPLCancelMaintainSubliDao;
    @Autowired
    OrgzationDao orgzationDao;
    @Autowired
    FileService fileService;
    @Autowired
    IFormCodeService formCodeService;
    @Autowired
    BaseInfoDao baseInfoDao;
    @Autowired
    Environment environment;
    @Autowired
    WfCompletedTaskMapper wfCompletedTaskMapper;

    @Autowired
    PropertyService propertyService;

    @Autowired
    @Lazy
    private FormWorkflowService formWorkflowService;

    @Autowired
    private GzwProperties gzwProperties;

    @Autowired
    private CqzcNplcancelmaintainMapper cqzcNplcancelmaintainMapper;

    @Autowired
    private INplcancelmaintainsubliaService nplcancelmaintainsubliaService;

    @Autowired
    private IOrgService orgService;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private IApprovalMessageService approvalMessageService;

    /**
     * logger属性.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(NPLCancelMaintainService.class);

    /**
     * 保存
     *
     * @param pd
     * @return
     */
    public ObjResult save(PageData pd) {
        try {
            pd.put("id", UuidUtil.get32UUID());
            pd.put("orgId", TokenUtil.getTokenOrgId());
            pd.put("code", formCodeService.getCode(FormTypeConstant.CQZC_NPL_CANCEL_MAINTAIN));
            pd.put("formType", FormTypeConstant.CQZC_NPL_CANCEL_MAINTAIN);
            pd.put("createUser", TokenUtil.getTokenUserId());
            pd.put("createTime", new Date());
            pd.put("updateUser", TokenUtil.getTokenUserId());
            pd.put("updateTime", new Date());
            nPLCancelMaintainDao.save(pd);
            fileService.edit(pd.getString("id"), (List<HashMap>) pd.get("list_doc"));
            ObjectMapper mapper = new ObjectMapper();
            List<PageData> listSubli = mapper.convertValue((List<PageData>) pd.get("listSubli"),
                    new TypeReference<List<PageData>>() {
                    });
            if (listSubli != null && listSubli.size() > 0) {
                saveSubli(listSubli, pd.getString("id"));
            }
            HashMap<String, Object> processVariable = new HashMap<>();
            formWorkflowService.startProcessAndSimulate(pd.getString("id"), pd.getString("formType"), processVariable);
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * submit
     *
     * @param nplcancelmaintain
     * @return
     */
    public ObjResult save(CqzcNplcancelmaintain nplcancelmaintain) {
        try {
            String uuid = null;
            if (StringUtils.isEmpty(nplcancelmaintain.getId())) {
                uuid = UuidUtil.get32UUID();
                nplcancelmaintain.setId(uuid);
                if (StringUtils.isEmpty(nplcancelmaintain.getOrgId())) {
                    nplcancelmaintain.setOrgId(TokenUtil.getTokenOrgId());
                }
                nplcancelmaintain.setCode(formCodeService.getCode(FormTypeConstant.CQZC_NPL_CANCEL_MAINTAIN));
                nplcancelmaintain.setFormType(String.valueOf(FormTypeConstant.CQZC_NPL_CANCEL_MAINTAIN));
                nplcancelmaintain.setStatus(String.valueOf(FormStatusConstant.UNREVIEWED));
                nplcancelmaintain.setCreateUser(TokenUtil.getTokenUserId());
                nplcancelmaintain.setCreateTime(new Date());
                nplcancelmaintain.setUpdateUser(TokenUtil.getTokenUserId());
                nplcancelmaintain.setUpdateTime(new Date());
                cqzcNplcancelmaintainMapper.insert(nplcancelmaintain);
                fileService.saveAll(uuid, nplcancelmaintain.getList_doc());
            } else {
                uuid = nplcancelmaintain.getId();
                nplcancelmaintain.setUpdateUser(TokenUtil.getTokenUserId());
                nplcancelmaintain.setUpdateTime(new Date());
                fileService.edit(uuid, nplcancelmaintain.getList_doc());
            }
            if (StringUtil.isNotBlank(nplcancelmaintain.getAttachIds())) {
                fileService.upYthFile(nplcancelmaintain.getAttachIds(), nplcancelmaintain.getId());
            }
            List<CqzcNplcancelmaintainsublia> listSubli = nplcancelmaintain.getListSubli();
            if (listSubli != null && listSubli.size() > 0) {
                saveSubliData(listSubli, uuid);
            }
            HashMap<String, Object> processVariable = new HashMap<>();
            // formWorkflowService.startProcessAndSimulate(uuid, nplcancelmaintain.getFormType(), processVariable);
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 修改
     *
     * @param pd
     * @return
     */
    public ObjResult edit(PageData pd) {
        try {
            pd.put("updateUser", TokenUtil.getTokenUserId());
            pd.put("updateTime", new Date());
            pd.put("reportingTime", new Date());
            nPLCancelMaintainDao.edit(pd);
            fileService.edit(pd.getString("id"), (List<HashMap>) pd.get("list_doc"));
            nPLCancelMaintainSubliDao.delByParent(pd.getString("id"));
            ObjectMapper mapper = new ObjectMapper();
            List<PageData> listSubli = mapper.convertValue((List<PageData>) pd.get("listSubli"),
                    new TypeReference<List<PageData>>() {
                    });
            if (listSubli != null && listSubli.size() > 0) {
                saveSubli(listSubli, pd.getString("id"));
            }
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 保存从表
     *
     * @param list
     * @param nplcancelmaintainId
     * @throws Exception
     */
    public void saveSubli(List<PageData> list, String nplcancelmaintainId) throws Exception {
        if (list != null && list.size() > 0) {
            for (PageData pageData : list) {
                pageData.put("nplcancelmaintainId", nplcancelmaintainId);
                pageData.put("id", UuidUtil.get32UUID());
            }
            nPLCancelMaintainSubliDao.saveAll(list);
        }
    }

    /**
     * @param list
     * @param nplcancelmaintainId
     * @throws Exception
     */
    public void saveSubliData(List<CqzcNplcancelmaintainsublia> list, String nplcancelmaintainId) throws Exception {
        if (list != null && list.size() > 0) {
            for (CqzcNplcancelmaintainsublia pageData : list) {
                if (StringUtils.isEmpty(pageData.getId())) {
                    pageData.setNplcancelmaintainId(nplcancelmaintainId);
                    pageData.setId(UuidUtil.get32UUID());
                }
            }
            nplcancelmaintainsubliaService.saveOrUpdateBatch(list);
        }
    }


    /**
     * 单据详情
     *
     * @param pd
     * @return
     */
    public ObjResult findbyid(PageData pd) {
        try {
            ObjResult objResult;
            PageData p = nPLCancelMaintainDao.findById(pd.getString("id"));
            List<PageData> listSubli = nPLCancelMaintainSubliDao.findById(pd.getString("id"));
            p.put("listSubli", listSubli);
            objResult = new ObjResult(CommonCode.SUCCESS);
            objResult.setPageData(p);
            return objResult;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 根据id删除
     *
     * @param ids
     * @return
     */
    public ObjResult del_ids(List<String> ids) {
        try {
            nPLCancelMaintainDao.del_ids(ids);
            for (String s : ids) {
                formWorkflowService.deleteProcessInstance(s);
            }
            return new ObjResult(CommonCode.SUCCESS);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
    }

    /**
     * 查询列表
     *
     * @return
     */
    public ListResult list(PageData pd) {
        ListResult listResult;
        try {
            pd.put("orgId", TokenUtil.getTokenOrgId());
            String status = pd.getString("status");
            if (null != status && !"".equals(status)) {
                pd.put("status", status.trim());
            }
            Page page = new Page(true, pd);
            List<PageData> list = nPLCancelMaintainDao.list(page);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }

    /**
     * 提交
     *
     * @param ids
     * @return
     */
    public HashMap<String, Object> commit(String ids){
        PageData pageData = new PageData();
        pageData.put("status", String.valueOf(FLOW));
        List<String> strings = new ArrayList<>();
        strings.add(ids);
        pageData.put("id", strings);
        try {
            nPLCancelMaintainDao.refer(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("上报失败");
        }
        return new HashMap<String, Object>();
    }

    /**
     * 退回单据
     *
     * @param formId 单据id
     */
    public Boolean reject(String formId, int formState, String comment){
        PageData pageData = new PageData();
        pageData.put("status", String.valueOf(formState));
        pageData.put("id", Collections.singletonList(formId));

        CqzcNplcancelmaintain nplcancelmaintain = cqzcNplcancelmaintainMapper.selectOne(Wrappers.<CqzcNplcancelmaintain>lambdaQuery().eq(CqzcNplcancelmaintain::getId, formId));
        if (Optional.ofNullable(nplcancelmaintain).isPresent()) {
            if (YthConstant.DATA_NINGBO.equals(nplcancelmaintain.getDataSource())) {
                ApprovalMessage approvalMessage = new ApprovalMessage();
                approvalMessage.setDataSourceId(nplcancelmaintain.getDataSourceId());
                approvalMessage.setOpinion(comment);
                approvalMessage.setIsApprove(1);
                approvalMessage.setIsSend(1);
                approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                approvalMessage.setFormType(Integer.valueOf(nplcancelmaintain.getFormType()));
                approvalMessageService.save(approvalMessage);
            }
        }
        try {
            nPLCancelMaintainDao.refer(pageData);
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException("回退失败");
        }
        return true;
    }

    /**
     * 审批完成
     *
     * @param formId
     */
    public Boolean finish(String formId) {
        try {
            PageData pageData = nPLCancelMaintainDao.findById(formId);
            pageData.put("status", String.valueOf(FINISH));
            pageData.put("updateTime", DateUtil.now());
            String code = formCodeService.getFilingCode(FormTypeConstant.CQZC_NPL_CANCEL_MAINTAIN);
            pageData.put("recordCode", gzwProperties.getCodeStartName() + "核备〔" + code.substring(0, 4) + "〕（" + code.substring(code.length() - 3, code.length()) + "）号（汇）");

            CqzcNplcancelmaintain nplcancelmaintain = cqzcNplcancelmaintainMapper.selectOne(Wrappers.<CqzcNplcancelmaintain>lambdaQuery().eq(CqzcNplcancelmaintain::getId, formId));
            if (Optional.ofNullable(nplcancelmaintain).isPresent()) {
                if (YthConstant.DATA_NINGBO.equals(nplcancelmaintain.getDataSource())) {
                    ApprovalMessage approvalMessage = new ApprovalMessage();
                    approvalMessage.setDataSourceId(nplcancelmaintain.getDataSourceId());
                    approvalMessage.setOpinion("审批通过");
                    approvalMessage.setIsApprove(2);
                    approvalMessage.setIsSend(1);
                    approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                    approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                    approvalMessage.setFormType(Integer.valueOf(nplcancelmaintain.getFormType()));
                    approvalMessage.setFilingCode(nplcancelmaintain.getCode());
                    approvalMessageService.save(approvalMessage);
                }
            }
            nPLCancelMaintainDao.edit(pageData);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException("单据流转完成时修改单据状态失败！");
        }
        return true;
    }

    /**
     * 工作流
     *
     * @param formIds 单据ids
     */
    public List<PageData> findByIds(List<String> formIds) {
        try {
            PageData pageData = new PageData();
            pageData.put("ids", formIds);
            List<PageData> byIds = nPLCancelMaintainDao.findByIds(pageData);
            List<PageData> pageData1 = new ArrayList<>();
            for (PageData pd : byIds) {
                String unitname = pd.getString("UNITNAME");
                pd.put("orgName", unitname);
                pageData1.add(pd);
            }
            return pageData1;
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            throw new MyRuntimeException("根据单据id列表查询报表失败！");
        }
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(CQZC_NPL_CANCEL_MAINTAIN);
    }

    /**
     * 查询列表
     *
     * @return
     */
    public ListResult reportList(PageData pd) {
        ListResult listResult;
        try {
            Page page = new Page(true, pd);
            List<PageData> list = nPLCancelMaintainDao.reportListPage(page);
            listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            listResult = new ListResult(CommonCode.ERROR);
        }
        return listResult;
    }

    /**
     * 回到经办人
     *
     * @param formId
     */
    public void goBackToStash(String formId) {
        try {
            PageData pageData = new PageData();
            pageData.put("status", String.valueOf(UNREVIEWED));
            pageData.put("id", Collections.singletonList(formId));
            nPLCancelMaintainDao.refer(pageData);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }
    }

    public File createReceptFile(String id) throws Exception {
        PageData pd = nPLCancelMaintainDao.findById(id);
        List<PageData> list = nPLCancelMaintainSubliDao.findById(pd.getString("id"));
        Document document = new Document(com.itextpdf.text.PageSize.A4, 10, 10, 30, 40);
        FileOutputStream fs;
        BaseFont bfHeiTi;
        BaseFont bfST;
        BaseFont test;
        BaseFont bfbt;
        File pdffile = File.createTempFile(id.toString(), ".pdf");
        if (pdffile.exists()) {
            pdffile.delete();
        }
        fs = new FileOutputStream(pdffile.getPath());//getAbsolutePath
        PdfWriter.getInstance(document, fs);
        document.open();
        bfST = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        bfHeiTi = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        bfbt = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        test = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        // 添加标题
        Font font_Biaoti = new Font(bfHeiTi, 20.0f, Font.BOLD, BaseColor.BLACK);
        Font font_biaotou1 = new Font(test, 12.0f, Font.NORMAL, BaseColor.BLACK);
        Font font_biaotou2 = new Font(bfbt, 10.0f, Font.NORMAL, BaseColor.BLACK);
        Font font_Zhengwen = new Font(bfST, 11.0f, Font.NORMAL, BaseColor.BLACK);
        // 创建一个段落
        String title = pd.getString("year") + "年度不良资产核销备案表";
        Paragraph biaoti = new Paragraph(title, font_Biaoti);
        biaoti.setAlignment(1);
        biaoti.setSpacingAfter(20f);
        document.add(biaoti);
        // 创建副标题
        String recordCode = pd.getString("recordCode");
        if (recordCode == null) {
            recordCode = "";
        }
        String title1 = "备案编号:" + recordCode;
        title1 += "                   金额：万元 ";
        Paragraph biaoti1 = new Paragraph(title1, font_biaotou1);
        biaoti1.setAlignment(Element.ALIGN_CENTER);
        biaoti1.setSpacingAfter(10f);
//        biaoti1
        document.add(biaoti1);

        String[] head = {
                "不良资产核销企业名称",
                "类别",
                "账面原值",
                "账面净值",
                "核销净损失",
        };
        String[] kes = {
                "orgName",
                "cancelType",
        };
        //往来
        String[] kes1 = {
                "withMoneyLoss",
                "withMoneyNetBookValue",
                "withMoneyOriginalBookValue",
        };
        //实物
        String[] kes2 = {
                "physicalAssetsOriginalBookValue",
                "physicalAssetsNetBookValue",
                "physicalAssetsLoss",
        };
        String[] kes3 = {
                "investmentsAbroadLoss",
                "investmentsAbroadNetBookValue",
                "investmentsAbroadOriginalBookValue",
        };

        PdfPTable table = new PdfPTable(head.length);// 建立一个pdf表格

        PdfPCell cell = new PdfPCell(new Phrase("填报单位", font_Zhengwen));
        // 由四列变成一列
        cell.setColspan(1);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setPaddingBottom(5);
        cell.setPaddingTop(5);
        table.addCell(cell);
        PdfPCell cell2 = new PdfPCell(new Phrase(pd.getString("reportCompanyName"), font_Zhengwen));
        // 由四列变成一列
        cell2.setColspan(4);
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell2.setPaddingBottom(5);
        cell2.setPaddingTop(5);
        table.addCell(cell2);

        table.setSpacingBefore(10f);// 设置表格上面空白宽度
        table.setSpacingAfter(0f);// 设置表格下面空白宽度
        table.setSpacingBefore(10f);// 设置表格上面空白宽度
        table.setSpacingAfter(0f);// 设置表格下面空白宽度
        table.setTotalWidth(800);// 设置表格的宽度


        for (int i = 0; i < head.length; i++) {
            PdfPCell cell3 = new PdfPCell(new Phrase(head[i], font_Zhengwen));
            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell3.setPaddingBottom(5);
            cell3.setPaddingTop(5);
            table.addCell(cell3);
        }
//        PageData p=new PageData();
//        List<String> l=new ArrayList<>();
//        l.add("074");
//        p.put("parentId",l);
//       List<Tree> base= baseInfoDao.findTree(p);


        for (PageData pageData : list) {
            String cancelType = pageData.getString("cancelType");
            for (int i = 0; i < kes.length; i++) {
                String v = pageData.getString(kes[i]);
                PdfPCell cell3 = new PdfPCell(new Phrase(v, font_Zhengwen));
                cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell3.setPaddingBottom(5);
                cell3.setPaddingTop(5);
                cell3.setColspan(1);
                table.addCell(cell3);
            }
            if ("往来款项".equals(cancelType)) {
                for (int i = 0; i < kes1.length; i++) {
                    String v = pageData.getString(kes1[i]);
                    PdfPCell cell3 = new PdfPCell(new Phrase(v, font_Zhengwen));
                    cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell3.setColspan(1);
                    table.addCell(cell3);
                }
            } else if ("投资".equals(cancelType)) {
                for (int i = 0; i < kes3.length; i++) {
                    String v = pageData.getString(kes3[i]);
                    PdfPCell cell3 = new PdfPCell(new Phrase(v, font_Zhengwen));
                    cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell3.setColspan(1);
                    table.addCell(cell3);
                }
            } else {
                for (int i = 0; i < kes2.length; i++) {
                    String v = pageData.getString(kes2[i]);
                    PdfPCell cell3 = new PdfPCell(new Phrase(v, font_Zhengwen));
                    cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
                    cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    cell3.setColspan(1);
                    table.addCell(cell3);
                }
            }

        }
        PdfPCell cell3 = new PdfPCell(new Phrase("\n\n\n\n\n备案意见\n\n\n\n\n", font_Zhengwen));
        cell3.setColspan(1);
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell3);

        PdfPCell cell4 = new PdfPCell(new Phrase("\n\n\n\n\n\n\n\n\n(盖章)\n\n\n                                                                                             年        月         日", font_biaotou1));
        cell4.setColspan(4);
        cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(cell4);

        document.add(table);
        document.close();
        return pdffile;
    }

    public File buildword(String id, HttpServletResponse response) throws Exception {
        PageData pd = nPLCancelMaintainDao.findById(id);
        List<PageData> listSubli = nPLCancelMaintainSubliDao.findById(id);
        File file = null;
        try {
            if (pd != null) {
                Map<String, Object> data = new HashMap<>(16);
                data.put("year", pd.getString("year"));
                data.put("recordCode", pd.getString("recordCode"));
                data.put("reportCompanyName", pd.getString("reportCompanyName"));

                PageData findbycode = baseInfoDao.findbycode(pd.getString("orgId"));
                data.put("orgName", findbycode != null ? findbycode.getString("name") : "");

                //审批完的时间
                if (pd.getString("status").equals("3")) {
                    List<WfCompletedTask> wfCompletedTasks = wfCompletedTaskMapper.selectByFormId(id);
                    List<Date> dateList = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(wfCompletedTasks)) {
                        for (WfCompletedTask wfCompletedTask : wfCompletedTasks) {
                            dateList.add(wfCompletedTask.getFinishTime());
                        }
                    }
                    if (CollectionUtils.isNotEmpty(dateList)) {
                        Date max = Collections.max(dateList);
                        data.put("finishTime", max);
                    }
                }

                if (CollectionUtils.isNotEmpty(listSubli)) {
                    for (PageData pageData : listSubli) {
                        String cancelType = pageData.getString("cancelType");
                        if ("往来款项".equals(cancelType)) {
                            pageData.put("physicalAssetsOriginalBookValue", new BigDecimal(pageData.getString("withMoneyOriginalBookValue")));
                            pageData.put("physicalAssetsNetBookValue", new BigDecimal(pageData.getString("withMoneyNetBookValue")));
                            pageData.put("physicalAssetsLoss", new BigDecimal(pageData.getString("withMoneyLoss")));
                        }
                        if ("投资".equals(cancelType)) {
                            pageData.put("physicalAssetsOriginalBookValue", new BigDecimal(pageData.getString("investmentsAbroadOriginalBookValue")));
                            pageData.put("physicalAssetsNetBookValue", new BigDecimal(pageData.getString("investmentsAbroadNetBookValue")));
                            pageData.put("physicalAssetsLoss", new BigDecimal(pageData.getString("investmentsAbroadLoss")));
                        }
                    }
                } else {
                    PageData p = new PageData();
                    p.put("physicalAssetsOriginalBookValue", "");
                    p.put("physicalAssetsNetBookValue", "");
                    p.put("physicalAssetsLoss", "");
                    listSubli.add(p);
                }
                data.put("listSubli", listSubli);

                String recordCode = pd.getString("recordCode");
                String realPath = environment.getProperty("doc.path") + id + ".doc";
                ;
                if (recordCode == null) {
                    file = WordUtil.generateWord(data, realPath, "NPLCancelMaintain.doc", "NPLCancelMaintain.ftl");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
                } else {
                    file = WordUtil.generateWord(data, realPath, recordCode + ".doc", "NPLCancelMaintain.ftl");
                    String fileName = new String(file.getName().getBytes("GB2312"), "ISO_8859_1");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
                }

                InputStream inputStream = new FileInputStream(file);
                // 激活下载操作
                OutputStream os = response.getOutputStream();
                // 循环写入输出流
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }
                // 这里主要关闭。
                os.close();
                inputStream.close();
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return file;
    }

    /**
     * 接受数字宁波data
     *
     * @param data
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public String saveNPLCancelMaintainReform(String data) {
        YthResult ythResult = new YthResult();
        //成功的id集合
        List<String> successIds = new ArrayList<>();
        //失败的id集合
        List<String> failIds = new ArrayList<>();
        //失败的原因
        List<String> failReasons = new ArrayList<>();
        //将json字符串转换成list
        List<CqzcNplcancelmaintain> dataList = JSON.parseArray(data, CqzcNplcancelmaintain.class);
        //判断list是否为空
        if (CollectionUtil.isNotEmpty(dataList)) {
            //根据datasourceIds 查询出所有的数据
            List<CqzcNplcancelmaintain> list = cqzcNplcancelmaintainMapper.selectList(new LambdaQueryWrapper<CqzcNplcancelmaintain>()
                    .in(CqzcNplcancelmaintain::getDataSourceId, dataList.stream()
                            .map(CqzcNplcancelmaintain::getDataSourceId).toArray()));
            //如果数据库中有数据，就更新，没有就新增
            for (CqzcNplcancelmaintain entity : dataList) {
                String dataSourceId = entity.getDataSourceId();
                if (CollectionUtil.isNotEmpty(list)) {
                    List<String> olIds = list.stream().map(CqzcNplcancelmaintain::getDataSourceId).collect(Collectors.toList());
                    //判断数据库中是否有数据
                    if (olIds.contains(dataSourceId)) {
                        for (CqzcNplcancelmaintain oldEntity : list) {
                            if (dataSourceId.equals(oldEntity.getDataSourceId())) {
                                successIds.add(dataSourceId);
                                entity.setId(oldEntity.getId());
                                entity.setDataSource(YthConstant.DATA_NINGBO);
                                extracted(entity);
                                save(entity);
                                list.remove(oldEntity);
                                break;
                            }
                        }
                    } else {
                        //如果数据库中没有数据，就新增
                        entity.setDataSource(YthConstant.DATA_NINGBO);
                        extracted(entity);
                        save(entity);
                        successIds.add(entity.getDataSourceId());
                    }
                } else {
                    entity.setDataSource(YthConstant.DATA_NINGBO);
                    extracted(entity);
                    save(entity);
                    successIds.add(entity.getDataSourceId());
                }
            }
        } else {
            failReasons.add("数据为空");
        }
        ythResult.setSuccessIds(successIds);
        ythResult.setFailIds(failIds);
        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
        //ythResult转换成json字符串
        return JSON.toJSONString(ythResult);
    }

    /**
     * 将数字宁波过来的数据人员id，
     *
     * @param entity
     */
    private void extracted(CqzcNplcancelmaintain entity) {
        Map<String, String> orgSourceIds = orgService.getSourceId();
        Map<String, String> userSourceIds = userService.getSourceId();

        String orgId = orgSourceIds.get(entity.getOrgId());
        String createUser = userSourceIds.get(entity.getCreateUser());
        if (StringUtils.isNotBlank(orgId)) {
            entity.setOrgId(orgId);
            entity.setCreateCompanyId(orgId);
            entity.setReportCompanyId(orgId);
        }
        if (StringUtils.isNotBlank(createUser)) {
            entity.setCreateUser(createUser);
            entity.setUpdateUser(createUser);
        }
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        //从表
        if (CollectionUtil.isNotEmpty(entity.getListSubli())) {
            entity.getListSubli().forEach(item -> {
                if (StringUtils.isNotBlank(orgId)) {
                    item.setCreateCompanyId(orgId);
                }
                if (StringUtils.isNotBlank(item.getCancelCompanyName())) {
                    String propertyId = propertyService.findByOrgCode(item.getCancelCompanyName());
                    if(StringUtil.isNotBlank(propertyId)){
                        item.setCancelCompanyName(propertyId);
                    }
                }
            });
        }
    }
}
